package com.legolas.consumer.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.legolas.api.utils.Consts;
import com.legolas.consumer.service.activemq.QueueConsumer;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.exception.HystrixBadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import java.util.HashMap;
import java.util.Map;


/**
 * @author legolas
 * @date 2020/5/14 15:33
 */
@Service
public class ConsumerService {

    /**
     * 这里配置负载均衡策略loadbalance = "roundrobin",在dubbo-admin中可以配置访问两个provider的权重比
     * （这是一种不推荐的做法，它会严格按照权重比来进行访问），默认为Random，是按权重设置随机概率
     */
    @Reference(version = "1.0.0", group = "group1", retries = 0, timeout = 2000)
    private com.legolas.api.service.TestService testService1;

    @Reference(version = "1.0.0", group = "group2")
    private com.legolas.api.service.TestService testService2;

    @Autowired
    private QueueConsumer queueConsumer;

    public Map<String, Object> testGroup1(String name) {
        String result = testService1.test(name);
        Map<String, Object> hm = new HashMap<>();
        hm.put("name", result);
        return hm;
    }

    /*HystrixCommandProperties中有很多的配置信息*/
    //@HystrixCommand(fallbackMethod = "hello")
    public Map<String, Object> testGroup2(String name) {
        String result = testService2.test(name);
        Map<String, Object> hm = new HashMap<String, Object>();
        hm.put("name", result);
        return hm;
    }

    public Map<String, Object> hello(String name) {
        Map<String, Object> hm = new HashMap<String, Object>();
        hm.put("error", "testGroup2异常启用备用方案");
        return hm;
    }


    public String queueTest(String msg) {
        testService1.queueProducer(msg);
        try {
            return queueConsumer.consum(Consts.MQ_TEST_QUEUE_NAME);
        } catch (JMSException e) {
            e.printStackTrace();
            return "error";
        }
    }

}
